<template>
  <PanelHead :route="route"/>
  <div class="btns">
    <el-button :icon="Plus" type="primary" @click="open(null)" size="small">新增</el-button>
  </div>
<!-- 页面展示数据部分 -->
  <el-table :data="tableData.list" style="width: 100%;">
    <el-table-column prop="id" label="id"/>
    <el-table-column prop="name" label="昵称"/>
    <el-table-column prop="permissionName" label="菜单权限" width="500px" />
    <el-table-column label="操作">
      <template #default="scope">
        <!-- <el-button type="text" @click="edit(scope.row)"  @click="del(scope.row)">编辑</el-button> -->
        <el-button type="primary" @click="open(scope.row)">编辑</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页部分 -->
  <div class="pagination-info">
    <el-pagination
      v-model:current-page="paginationData.pageNum"
      :page-size="paginationData.pageSize"
      :background="background"
      size="small"
      layout="total, prev, pager, next"
      :total="tableData.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
  
  <!-- 弹窗部分  -->
  <el-dialog v-model="dialogFormVisible" :before-close="beforeClose" title="添加权限" width="500">

    <el-form ref="formRef" label-width="100px" label-position="left" :model="formData" :rules="rules">
      <!-- 隐藏的表单 -->
      <el-form-item v-show="false" prop="id">
        <el-input v-model="formData.id"/>
      </el-form-item>
      <el-form-item label="名称" prop="name">

        <el-input v-model="formData.name" placeholder="请输入权限名称"></el-input>
      </el-form-item>
      <el-form-item label="权限" prop="permissions">
        <el-tree ref="treeRef" style="max-width: 600px;" :data="permissionData" node-key="id" show-checkbox
          :default-checked-keys="defaultKeys" :default-expanded-keys="[2]" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="confirm(formRef)">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted , nextTick } from 'vue'
import { userGetMenu, userSetMenu, menuList } from '@/api/index'
import {Plus} from '@element-plus/icons-vue'
import { useRoute } from 'vue-router'

// onMounted(async()=>{
//   const res = await  userGetMenu()
//   console.log(res,'菜单管理')
// } )

const route = useRoute()

// 分页的两个函数
// 页码
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
}
// 当前页
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
}
// 列表数据
const tableData = reactive({
  list: [],
  total: 0,
})
// 页面列表数据按钮 打开弹窗
const open = (rowData = {})=>{
  dialogFormVisible.value = true
  // 弹窗打开form生成是异步的
  nextTick(()=>{
    if(rowData){
      Object.assign(formData,{id: rowData.id , name: rowData.name })
      treeRef.value.setCheckedKeys(rowData.permission)
    }
  })
}



// 表单数据
const formData = reactive({
  id: '',
  name: '',
  permissions: '',
  
})

// 表单实例
const formRef = ref()

// 树形菜单数据
const permissionData = ref([])

// 控制弹窗的隐藏和显示
const dialogFormVisible = ref(false)

// 关闭弹窗前的回调函数
const beforeClose = () => {
  dialogFormVisible.value = false
  // 重置表单
  formRef.value.resetFields()
  // tree选择重置
  treeRef.value.setCheckedKeys(defaultKeys)
}

// 选中权限
const defaultKeys = [4, 5]


// 表单验证规则
const rules = reactive({
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
  ],
  // permissions: [
  //   { required: true, message: '请选择权限', trigger: 'blur' },
  // ],
});


// tree的实例
const treeRef = ref()
// 表单数据 菜单数据
const fetchMenuData = async () => {
  try {
    const res = await userGetMenu();
    console.log('userGetMenu接口响应数据:', res.data); 
    permissionData.value = res.data.data
  } catch (error) {
    console.error('调用 userGetMenu 接口出错:', error);
  }
};
// 页面加载时调用接口
onMounted(() => {
  fetchMenuData();
  fetchListData()
})

const paginationData = reactive({
  pageNum: 1,
  pageSize: 10
});
// const listData = ref()
// 请求列表数据
const fetchListData = async () => {
  try {
    const res = await menuList(paginationData);
    console.log('menuList接口响应数据:', res.data); 
    const {list , total} = res.data
    tableData.list = list
    tableData.total = total  
  } catch (error) {
    console.error('调用 menuList 接口出错:', error);
  }
};


// 提交表单
const confirm = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async(valid, fields) => {
    if (valid) {
      //获取到选择的checkbox的数据
      const permissions = JSON.stringify(treeRef.value.getCheckedKeys())
      const res = await userSetMenu({ name: formData.name, permissions, id: formData.id })
      console.log(res, 'res里需要的数据')
      beforeClose()
      fetchListData()
    } else {
      console.log('error submit!', fields);
    }
  })
}


// 分页开关
const disabled = ref(false)
const background = ref(false)
</script>

<style scoped>
.pagination-info {
  margin-top: 10px;
  float: right;
}

.btns {
  padding: 10px 0 10px 10px;
  background-color: #fff;
}
</style>